package craw

import (
	"github.com/axgle/mahonia"
	"github.com/gocolly/colly/v2"
	"io"
	"log"
	"net/http"
	"os"
)

var TaroPages = []string{"http://www.tarot5.cn/photo/tarot/tarot_84_1.htm",
	"http://www.tarot5.cn/photo/tarot/tarot_84_2.htm",
	"http://www.tarot5.cn/photo/tarot/tarot_84_3.htm",
	"http://www.tarot5.cn/photo/tarot/tarot_84_4.htm"}

type CrawImg struct {
	imgColly *colly.Collector
}

func NewCrawImg() *CrawImg {
	crawImg := &CrawImg{}
	crawImg.imgColly = colly.NewCollector()
	return crawImg
}

// ConvertToString
// 改变抓取结果的编码方式 从gbk转换为utf-8
func ConvertToString(src string, srcCode string, tagCode string) string {

	srcCoder := mahonia.NewDecoder(srcCode)

	srcResult := srcCoder.ConvertString(src)

	tagCoder := mahonia.NewDecoder(tagCode)

	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)

	result := string(cdata)

	return result

}

//CrawImgLinks
//获得图片以及该图片对应的名称
func (ci *CrawImg) CrawImgLinks(url string) map[string]string {
	resourseMap := map[string]string{}
	ci.imgColly.OnHTML("body>.taluopai>.tarot_2>.t2_photo_3", func(e *colly.HTMLElement) {
		downloadLinks := e.ChildAttrs("img", "src")
		picNames := e.ChildTexts("a")
		for i := 0; i < len(picNames); i++ {
			picNames[i] = ConvertToString(picNames[i], "gbk", "utf-8")
			resourseMap[picNames[i]] = downloadLinks[i]
		}
	})

	ci.imgColly.Visit(url)

	return resourseMap
}

//DownloadResources
//下载图片
// 这个函数可以使用携程来完成
func (ci *CrawImg) DownloadResources(link string) error {
	for _, url := range TaroPages {
		pictureAndLinkMaps := ci.CrawImgLinks(url)

		// 获取该链接下的所有图片和链接
		for name, link := range pictureAndLinkMaps {
			log.Println("name is: ", name, "\t and link is:  ", link)
			log.Println("Start to download the picture...")
			ImgHttpGet(name, link)
		}
	}

	return nil
}

func ImgHttpGet(filename string, downloadLink string) error {
	resp, err := http.Get(downloadLink)
	if err != nil {
		return err
	}
	file, err := os.Create("/Users/apple/WeChatProjects/miniprogram-1/img/" + filename + ".jpg")
	defer file.Close()

	_, err = io.Copy(file, resp.Body)
	if err != nil {
		return err
	}

	return nil
}
